package com.mikey.tvolatile;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :Mikey
 * @description :不保证原子性
 * @create :2022-09-27 13:56:00
 */
public class Demo {
//    不保证原子性
    private volatile static AtomicInteger num=new AtomicInteger(0);
    public  static  void add(){
        //num++;//不是一个原子性操作
        num.getAndIncrement();//AtomicInteger +1方法 ，底层CAS
    }
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+"    "+num);
    }
}
